using System;
using System.Reflection;
using System.Collections.Generic;

namespace DecoratorDemo
{
    public class DecoratorFactory
    {
        private static Type TypeOfDecoratorAttribute = typeof(DecoratorAttribute);

        public static IDecorator CreateBeDecorator<TDecorator>(string identity) where TDecorator : IDecorator
        {
            Type typeOfTDecorator = typeof(TDecorator);
            IDecorator decorator = Activator.CreateInstance(typeof(TDecorator), identity) as IDecorator;

            if (typeOfTDecorator.IsDefined(TypeOfDecoratorAttribute, true))
            {
                // IEnumerable<DecoratorAttribute> decoratorAttributes = typeOfTDecorator.GetCustomAttributes<DecoratorAttribute>(true);
                // foreach (var decoratorAttribute in decoratorAttributes)
                foreach (var decoratorAttribute in typeOfTDecorator.GetCustomAttributes<DecoratorAttribute>(true))
                {
                    decorator = Activator.CreateInstance(decoratorAttribute.DecoratorType, decorator) as IDecorator;
                }
            }

            return decorator;
        }
    }
}
